const labelService = require("../service/label.service");

const verifyLabelExists = async (ctx, next) => {
    // 1.获取用户传递的labels
    const { labels } = ctx.request.body;
    // 2. 获取label的name 判断label表中是否存在
    const newLabels = [];
    for (const name of labels) {
        const result = await labelService.queryLabelByName(name);
        const labelObj = { name }
        if (result) {
            // 存在：获取name对应label的id
            labelObj.id = result.id
        } else {
            const insertResult = await labelService.create(name);
            labelObj.id = insertResult.insertId
        }
        newLabels.push(labelObj)
    }
    // 3. 所有的labels都变成了 [{name:'',id:}]
    // console.log(newLabels);
    ctx.labels = newLabels;
    await next()
}

module.exports = {
    verifyLabelExists
}